<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/12/21
 * Time: 10:18
 */

namespace Shop\Api;


use Common\Api\Api;
use Shop\Model\RedEnvelopeModel;
use Shop\Model\VUserRedEnvelopeModel;
use Admin\Api\MemberApi;
use Admin\Api\MessageApi;
use Admin\Model\MessageModel;

class RedEnvelopeApi extends Api {

    /**
     * 注册送红包
     */
    const REG_ADD = "Shop/RedEnvelope/reg_add";
    /**
     * 添加
     */
    const ADD = "Shop/RedEnvelope/add";
    /**
     * 保存
     */
    const SAVE = "Shop/RedEnvelope/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "Shop/RedEnvelope/saveByID";

    /**
     * 删除
     */
    const DELETE = "Shop/RedEnvelope/delete";

    /**
     * 查询
     */
    const QUERY = "Shop/RedEnvelope/query";
    /**
     * 查询
     */
    const API_QUERY = "Shop/RedEnvelope/queryWithCount";

    /**
     * 查询一条数据
     */
    const GET_INFO = "Shop/RedEnvelope/getInfo";
    /**
     * 包含红包模版信息的一条数据
     */
    const GET_INFO_WITH_EXTRA = "Shop/RedEnvelope/getInfoWithExtra";

    /**
     * 不分页查询
     */
    const QUERY_WITH_TPL = "Shop/RedEnvelope/queryWithTpl";

    const SEND_SHOPPING_ENVOLOPE = "Shop/RedEnvelope/sendShoppingEnvolope";

    const SEND_TO_USER = "Shop/RedEnvelope/sendToUser";
    const USEFUL_COUNT = "Shop/RedEnvelope/userfulCount";

    protected function _init(){
        $this->model = new RedEnvelopeModel();
    }

    /**
     * 发送给用户红包，可指定面额和时间
     * 若有消息推送 最好放外面 适应业务逻辑
     * rainbow - boye010@163.com
     * @param  [type]  $uid         [description]
     * @param  [type]  $tpl_id      [description]
     * @param  string  $notes       [description]
     * @param  integer $money       面额,0将使用模板面额
     * @param  integer $expire_time 时限,0将使用模板时限
     * @param  boolean $push        是否推送
     * @return array                api-Return
     */
    public function sendToUser($uid,$tpl_id,$notes='',$money=0,$expire_time=0,$push=false){

        $r = apiCall(MemberApi::GET_INFO,array(array('uid'=>$uid)));
        if(!$r['status']) return $this->apiReturnErr($r['info']);
        if(empty($r['info'])) return $this->apiReturnErr('uid错误：'.$uid);

        $money = floatval($money);
        $expire_time = intval($expire_time);
        if($money<0 || $expire_time<0) return $this->apiReturnErr('参数错误：'.$money.'-'.$expire_time);

        $r = apiCall(RedEnvelopeTplApi::GET_INFO,array(array('id'=>$tpl_id)));
        if($r['status']){
            if(empty($r['info'])) return $this->apiReturnErr('红包模板错误'.$tpl_id);
            if($r['info']['dtree_type'] == getDatatree('RED_TEN_PERCENT')){
                return $this -> apiReturnErr('不支持此类型红包');
            }
            $money = $money ? $money : $r['info']['money'];
            $expire_time = $expire_time ? $expire_time : $r['info']['expire_time'];
        }else{
            return $this -> apiReturnErr($r['info']);
        }

        $entity = array(
            'notes'       =>$notes,
            'uid'         =>$uid,
            'get_time'    =>time(),
            'use_status'  =>RedEnvelopeModel::NOT_USE,
            'tpl_id'      =>$tpl_id,
            'money'       =>$money,
            'expire_time' =>$expire_time,
        );
        $r = $this->add($entity);
        if(!$r['status']) return $r;
        if($push){
            $entity = array(
                'from_id' =>0,
                'title'   =>MessageModel::MESSAGE_SYSTEM,
                'content' =>'您获得一张'.$money.'元红包',
                'summary' =>'您获得一张'.$money.'元红包',
                'extra'   =>'', //消息记录中的
            );
            $after_open = array('type'=>'go_activity','param'=>MessageModel::MESSAGE_SYSTEM_ACTIVITY,'extra'=>array()); //推送参数
            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,array(MessageModel::MESSAGE_SYSTEM,$entity,$uid,false,$after_open));
            if(!$r['status']) return $this->apiReturnSuc($r['info']);
            return $this->apiReturnSuc('发送成功');
        }else{
            return $this->apiReturnSuc('发送成功');
        }
    }
    public function userfulCount($map,$time_map){
        $count = $this -> model -> where($map) -> where($time_map) -> count();
        if($count === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }else{
            return $this -> apiReturnSuc($count);
        }
    }

    public function queryWithTpl($uid,$use_status = false){

        $query = $this -> model -> join("left join (select id as t_id,use_condition,dtree_type from itboye_red_envelope_tpl) as tpl on tpl_id=tpl.t_id") -> join("(select id as type_id,name from common_datatree) as datatree on datatree.type_id=tpl.dtree_type");

        $map = array(
            'itboye_red_envelope.uid' => $uid,
        );
        if($use_status !== false){
            $map['use_status'] = $use_status;
        }
        $result = $query -> where($map) -> select();

        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }else{
            return $this -> apiReturnSuc($result);
        }

    }

    /**
     * 消费送红包
     * @param $uid
     * @param $money 消费总额
     */
    public function sendShoppingEnvolope($uid,$money){

        $tpl_id = 8;
        $map = array(
            'status' => 1,
            'id' => $tpl_id,
        );
        $result = apiCall(RedEnvelopeTplApi::GET_INFO,array($map));
        if($result['status']){
            $rate = $result['info']['money'];
            $notes = $result['info']['notes'];
            $expire_time = $result['info']['expire_time'];
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        if($rate*$money<1){
            $this->apiReturnSuc('红包金额小于1，不发');
        }

        $entity = array(
            'uid' => $uid,
            'get_time' => time(),
            'tpl_id' => 8,
            'use_status' => 0,
            'notes' => $notes,
            'money' => $rate*$money,
            'expire_time' => $expire_time,
        );
        $result = $this -> model -> create($entity,1);
        if ($result === false) {
            $error = $this -> model -> getError();
            return $this -> apiReturnErr($error);
        } else {
            $result = $this -> model -> add();
            if ($result === false) {
                return $this -> apiReturnErr($this -> model -> getDbError());
            }
            return $this -> apiReturnSuc($result);
        }

    }

    /**
     * 注册送红包 1张50(id=3) 5张10(id=4)
     * @param $uid
     */
    public function reg_add($uid){

        $money = array();
        $notes = array();
        $expire_time = array();

        //查询50元红包信息
        $map = array(
            'status' => 1,//开启
            'id' => 3,
        );
        $result = apiCall(RedEnvelopeTplApi::GET_INFO,array($map));
        if($result['status']){
            $money[0] = $result['info']['money'];
            $notes[0] = $result['info']['notes'];
            $expire_time[0] = $result['info']['expire_time'];
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        $map = array(
            'status' => 1,//开启
            'id' => 4,
        );
        $result = apiCall(RedEnvelopeTplApi::GET_INFO,array($map));
        if($result['status']){
            $money[1] = $result['info']['money'];
            $notes[1] = $result['info']['notes'];
            $expire_time[1] = $result['info']['expire_time'];
        }else{
            return $this -> apiReturnErr($result['info']);
        }

        $entity[0] = array(
            'uid' => $uid,
            'get_time' => time(),
            'tpl_id' => 3,
            'use_status' => 0,
            'notes' => $notes[0],
            'money' => $money[0],
            'expire_time' => $expire_time[0],
        );
        for($i = 1;$i<=5;$i++){
            $entity[$i] = array(
                'uid' => $uid,
                'get_time' => time(),
                'tpl_id' => 4,
                'use_status' => 0,
                'notes' => $notes[1],
                'money' => $money[1],
                'expire_time' => $expire_time[1],
            );
        }

        $result = $this -> model -> addAll($entity);

        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }else{
            return $this -> apiReturnSuc('红包添加成功！');
        }

    }

    public function getInfoWithExtra($map,$order=false){
        $this->model = new VUserRedEnvelopeModel();
        if($order === false){
            $result = $this -> model -> where($map) -> find();
        }else{
            $result = $this->model->where($map)->order($order)->find();
        }

        if ($result === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        } else {
            return $this -> apiReturnSuc($result);
        }
    }

    public function queryWithCount($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $this->model = new VUserRedEnvelopeModel();
        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }

        $list = $query-> page($page['curpage'] . ',' . $page['size'])->where($map) -> select();
        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        $count = $this -> model -> where($map) -> count();

        return $this -> apiReturnSuc(array("count" => $count, "list" => $list));
    }

    public function query($map = null, $page = array('curpage'=>0,'size'=>10), $order = false, $params = false, $fields = false) {
        $this->model = new VUserRedEnvelopeModel();
        $query = $this->model;
        if(!is_null($map)){
            $query = $query->where($map);
        }
        if(!($order === false)){
            $query = $query->order($order);
        }
        if(!($fields === false)){
            $query = $query->field($fields);
        }

        $list = $query-> page($page['curpage'] . ',' . $page['size'])->where($map) -> select();

        if ($list === false) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new \Think\Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params !== false) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();

        return $this -> apiReturnSuc(array("show" => $show, "list" => $list));
    }

}